package com.erp.framework.web;

import com.erp.framework.util.user.User;
import com.erp.app.common.ProjectConstants;

import org.apache.struts.action.*;
import org.apache.struts.util.MessageResources;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Locale;

public class SimpleAction extends Action {

	public static final String actionAdd = "add";
	public static final String actionDelete = "delete";
	public static final String actionSave = "save";
	public static final String actionSearch = "search";
	public static final String actionCancel = "cancel";
	public static final String actionExit = "exit";
	public static final String actionScroll = "scroll";
	public static final String actionClear = "clear";
	public static final String actionEdit = "edit";
	public static final String actionCreate = "create";

    public final ActionForward perform(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response) throws ServletException {

        //beforeExecuteAction(mapping, formIn, request, response);
        ActionForward forward = null;
		try {
			forward = execute(mapping, formIn, request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //afterExecuteAction(mapping, formIn, request, response);
        return forward;
    }

    public ActionForward execute(ActionMapping mapping,
	                             ActionForm formIn,
	                             HttpServletRequest request,
	                             HttpServletResponse response)
	        throws Exception {
		ActionForward actionForward = null;
		try {
		
			HttpSession session = request.getSession(false);
			Locale locale = (Locale) session.getAttribute(Action.LOCALE_KEY);
			ActionErrors errors = new ActionErrors();
//			MessageResources messages = getResources(request);
	
			actionForward = new ActionForward(mapping.getInput());
	
			boolean handled = false;
	
			// Check login status before procceeding...
			if (!hasLogin(request)) {
				actionForward = mapping.findForward("login");
				handled = true;
			}
	
			// check for permission to access
			User editingUser = (User)session.getAttribute(ProjectConstants.SESSION_USER);
			String functionId = getFunctionId(formIn);
			if (functionId == null) {
				String requestURI = request.getRequestURI();
				if (requestURI != null)
					functionId = requestURI.substring(requestURI.lastIndexOf("/") + 1);
			}
			/*
			if (!handled && !hasAccessRight(functionId, editingUser)) {
				actionForward = mapping.findForward("default");
				handled = true;
			}
			*/
	
			if (!handled) {
				actionForward = handlePageEvent(mapping, formIn, request, response, errors);
				handled = true;
			}
	
            setInitParam(mapping, formIn, request, response, errors);
			saveErrors(request, errors);
			saveToken(request);
			
		} catch (Exception e) {
			Logger.getLogger(this.getClass().getName()).error(e.getMessage(), e);
		} finally {
		
			response.setHeader("Expires", "Tue, 28 Dec 1993 23:59:59 GMT");
	        response.setHeader("Pragma", "no-cache");
	        response.setHeader("Cache-control", "no-cache");
		}
		
		return actionForward;
	}

    protected void setInitParam(ActionMapping mapping,
            ActionForm formIn,
            HttpServletRequest request,
            HttpServletResponse response,
            ActionErrors errors) {
    }

    protected boolean hasLogin(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		User editingUser = null;
		if (session == null)
			return false;
		else {
			editingUser = (User)session.getAttribute(ProjectConstants.SESSION_USER);
			return (editingUser != null);
		}
	}

	protected String getFunctionId(ActionForm formIn) {
		return null;
	}


	protected boolean hasAccessRight(String menuId, User editingUser) {
		boolean hasRight = true;
//		try {
//			hasRight = editingUser.canAccess(menuId);
//		} catch (Exception e) {
//			Logger.getLogger(this.getClass().getName()).error(e.getMessage(), e);
//		}
		return hasRight;
	}

	protected ActionForward handlePageEvent(ActionMapping mapping,
	                                        ActionForm formIn,
	                                        HttpServletRequest request,
	                                        HttpServletResponse response,
	                                        ActionErrors errors) {
		return new ActionForward(mapping.getInput());
	}

//	protected MastersDelegate getMasterDelegate(HttpSession session) {
//		try {
//			String nameInSession = getDelegateSessionName();
//			if (session.getAttribute(nameInSession) != null) {
//				return (MastersDelegate) session.getAttribute(nameInSession);
//			} else {
//				MastersDelegate dg = newMasterDelegate();
//				session.setAttribute(nameInSession, dg);
//				return dg;
//			}
//		} catch (Exception e) {
//			Logger.getLogger(this.getClass().getName()).error(e.getMessage(), e);
//		}
//		return null;
//	}
//
//	protected void removeMasterDelegate(HttpSession session) {
//		try {
//			String nameInSession = getDelegateSessionName();
//
//			getMasterDelegate(session).removeSessionBean();
//			session.removeAttribute(nameInSession);
//		} catch (Exception e) {
//			Logger.getLogger(this.getClass().getName()).error(e.getMessage(), e);
//		}
//	}// end removeSession

//	final protected String getDelegateSessionName() {
//		return "SESSION_MASTER_DELEGATE." + (newMasterDelegate().getClass().getName());
//	}

//	protected MastersDelegate newMasterDelegate() {
//		return new MastersDelegate();
//	}

}

